/**
 * 
 */
package org.dragonfire.irc.server.routing;

import java.util.TreeMap;
import java.util.TreeSet;

import org.dragonfire.irc.messages.Message;
import org.dragonfire.irc.messages.ServerMessage;
import org.dragonfire.irc.server.ServerConnection;

/**
 * @author Darth Android
 * @date Oct 30, 2007
 */
public class MessageRouter {

	private TreeMap<String, TreeSet<Route>> routes = new TreeMap<String, TreeSet<Route>>();

	public void addRoute(Route route) {
		synchronized (routes) {
			if (!routes.containsKey(route.getName()))
				routes.put(route.getName(), new TreeSet<Route>());
		}
		TreeSet<Route> currentRoutes = routes.get(route.getName());
		synchronized (currentRoutes) {
			currentRoutes.add(route);
		}

	}

	public void addRoute(String name, ServerConnection connection, int distance) {
		addRoute(new Route(name, connection, distance));
	}

	public boolean isVisibleServer(String name) {
		return routes.containsKey(name);
	}

	public String[] getVisibleServers() {
		return routes.keySet().toArray(new String[routes.size()]);
	}

	public Route getRoute(String name) {
		return isVisibleServer(name) ? routes.get(name).first() : null;
	}

	public void routeMessage(Message m) {

	}

	public void broadcastMessage(Message message) {
		String[] servers = getVisibleServers();
		for (String server : servers) {
			ServerMessage sm = new ServerMessage(message);
			sm.setDestination(server);
			routeMessage(sm);
		}
	}

}
